<script setup lang="ts" name="TallyInBatchForm">
import { onMounted, reactive, ref } from "vue";
import SelectStorage from "@/components/SelectInfo/SelectStorage.vue";
import SelectPosition from "@/components/SelectInfo/SelectPosition.vue";
import SelectPackageType from "@/components/SelectInfo/SelectPackageType.vue";
import type {
  PackageTypeData,
  PositionData,
  StorageData
} from "@/utils/interface";
import BigNumber from "bignumber.js";
import { useBillInfo } from "@/store/bill-info";
import { useEditOstInfo } from "@/store/edit-ost-info";
import { isNumeric } from "vant/es/utils";
import YardMapV2 from "@/components/TallyType/YardMapV2.vue";
import { deepClone } from "vant/es/utils/deep-clone";

const themeVars = {
  cellLabelFontSize: "13px",
  cellLabelColor: "#7f7e7e",
  numberKeyboardZIndex: 1000,
  radioDotSize: "5px",
  navBarTitleTextColor: "#ffffff",
  navBarIconColor: "#ffffff",
  fontBold: 0,
  popupBackground: "#f6f6f6",
  calendarPopupHeight: "40%",
  cellHorizontalPadding: "20px"
};

const billInfo = ref({} as any);
// const emit = defineEmits(["result"]);

const perTon = ref(0);

const emit = defineEmits(["isOpen", "formData"]);

const validator = (val: any) => isNumeric(val);
const showYard = ref(false);
const showSelectPackageTypePopup = ref(false);
const showSelectPositionPopup = ref(false);
const isSpotSelect = ref("Y");
const showSelectStoragePopup = ref(false);
const billInfoStore = useBillInfo();
const editOstInfoStorage = useEditOstInfo();

onMounted(() => {
  init();
});
billInfoStore.$subscribe(() => {
  init();
});

function init() {
  billInfo.value = billInfoStore.billInfo;

  if (!editOstInfoStorage.editOstInfo.tallyPackageType) {
    formData.tallyPackageType = billInfo.value.packageType;
    formData.tallyPackageTypeName = billInfo.value.packageTypeName;

    if (formData.tallyPackageType === "BU") {
      formData.tallyPiece = "0";
      formData.tallyTon = "0";
    }
  }

  planPieceTon.value = billInfo.value?.piece + "/" + billInfo.value?.ton;
  storagePieceTon.value =
    billInfo.value?.storagePiece + "/" + billInfo.value?.storageTon;
  if (billInfo.value.piece !== 0) {
    const ton = new BigNumber(billInfo.value.ton);
    const piece = new BigNumber(billInfo.value.piece);
    perTon.value = ton.div(piece).toNumber();
  }
}

const formData = reactive({
  tallyTon: "",
  tallyPiece: "",
  positionInfo: {} as PositionData,
  spot: "",
  areaCode: "",
  tallyPackageType: "",
  tallyPackageTypeName: "",
  storageAreaId: "",
  storageAreaName: "",
  storagePositionId: "",
  storagePositionName: "",
  goodsPositionId: ""
});

const planPieceTon = ref("");
const storagePieceTon = ref("");

const isSelectPackageTypeOpen = (value: boolean) => {
  showSelectPackageTypePopup.value = value;
};
const selectedPackageType = (value: PackageTypeData) => {
  formData.tallyPackageType = "";
  formData.tallyPackageTypeName = "";
  formData.tallyPackageType = value.customsPackageCode;
  formData.tallyPackageTypeName = value.packInfo;
};

const isSelectPositionOpen = (value: boolean) => {
  showSelectPositionPopup.value = value;
};
const selectedPosition = (value: PositionData) => {
  formData.positionInfo = {} as PositionData;
  formData.storagePositionName = "";

  if (value.areaId) {
    formData.positionInfo = value;

    formData.storageAreaId = value.areaId;
    formData.storageAreaName = value.areaName;
    formData.storagePositionId = value.id;
    formData.storagePositionName = value.name;
    formData.areaCode = value.code;
  }
};

const isSelectStorageOpen = (value: boolean) => {
  showSelectStoragePopup.value = value;
};
const selectedStorage = (res: StorageData) => {
  formData.spot = res.spot;
  formData.tallyPackageType = res.packageType;
  formData.tallyPackageTypeName = res.packageTypeName;
  formData.tallyPiece = String(res.piece);
  formData.tallyTon = res.ton;
  formData.goodsPositionId = res.goodsPositionId;
  formData.areaCode = res.areaCode;
};

function showPop(show: boolean) {
  emit("isOpen", show);
}

const onSelectedArea = (e: any) => {
  showYard.value = false;
  if (isSpotSelect.value) {
    formData.spot = e.names;
  }
  formData.goodsPositionId = e.id;
};

function setTon() {
  setPerTon();
  if (formData.tallyPiece && perTon.value) {
    formData.tallyTon = new BigNumber(formData.tallyPiece as string)
      .times(perTon.value)
      .toString();
  }
}

function setPerTon() {
  billInfo.value = billInfoStore.billInfo;
  if (billInfo.value.transportBillId && billInfo.value.piece !== 0) {
    const ton = new BigNumber(billInfo.value.ton);
    const piece = new BigNumber(billInfo.value.piece);
    perTon.value = Number(ton.div(piece).toFixed(3));
  }
}

function resetForm() {
  formData.tallyTon = "";
  formData.tallyPiece = "";
  formData.positionInfo = {} as PositionData;
  formData.spot = "";
  formData.areaCode = "";
  formData.tallyPackageType = billInfo.value.packageType;
  formData.tallyPackageTypeName = billInfo.value.packageTypeName;
  formData.storageAreaId = "";
  formData.storageAreaName = "";
  formData.storagePositionId = "";
  formData.storagePositionName = "";
  formData.goodsPositionId = "";
}

function returnData() {
  emit("formData", deepClone(formData));
  showPop(false);
  resetForm();
}
</script>

<template>
  <div class="flex-col h-[full] p-[20px] w-full" style="background: #f6f6f6">
    <van-config-provider :theme-vars="themeVars">
      <div class="flex h-[30px] justify-between mb-[10px]">
        <div
          class="flex justify-center items-center h-full text-center text-base font-bold"
        >
          入库
        </div>
        <div
          class="flex h-full justify-center items-center text-center text-base"
        >
          <div class="mr-[30px]" @click="resetForm">重置</div>
          <div class="text-blue-500 font-bold" @click="returnData">确定</div>
        </div>
      </div>

      <div>
        <van-form>
          <van-field
            readonly
            v-model="planPieceTon"
            name="planPieceTon"
            label="计划件吨"
          />
          <van-field
            readonly
            v-model="storagePieceTon"
            name="storagePieceTon"
            label="库存件吨"
          />
          <van-field
            readonly
            name="position"
            label="货场"
            placeholder="请选择货场"
            is-link
            v-model="formData.storagePositionName"
            @click="showSelectPositionPopup = true"
            :rules="[{ required: true, message: '请选择货场' }]"
          >
            <template #label> 货场<span class="xing">*</span></template>
          </van-field>
          <van-popup
            v-model:show="showSelectPositionPopup"
            position="bottom"
            round
            duration="0"
            :style="{ height: 'auto' }"
          >
            <SelectPosition
              :position="{
                value: formData.positionInfo?.id,
                text: formData.positionInfo?.name
              }"
              @isOpen="isSelectPositionOpen"
              @selectedPosition="selectedPosition"
            ></SelectPosition>
          </van-popup>
          <van-field
            name="timeSpace"
            label="重垛"
            :rules="[{ required: true, message: '请选择是否重垛' }]"
          >
            <template #input>
              <van-radio-group
                shape="dot"
                v-model="isSpotSelect"
                direction="horizontal"
              >
                <van-radio name="Y" icon-size="18px">是</van-radio>
                <van-radio name="N" icon-size="18px">否</van-radio>
              </van-radio-group>
            </template>
          </van-field>
          <van-field
            v-if="isSpotSelect === 'N'"
            name="position"
            label="货位"
            v-model="formData.spot"
            placeholder="请填写货位并绘制地图"
            :rules="[{ required: true, message: '请填写货位' }]"
          >
            <template #label> 货位<span class="xing">*</span></template>
            <template #button>
              <van-button size="small" type="primary" @click="showYard = true"
              >绘图
              </van-button
              >
            </template>
          </van-field>
          <van-field
            v-if="isSpotSelect === 'Y'"
            name="position"
            label="货位"
            readonly
            v-model="formData.spot"
            @click="showSelectStoragePopup = true"
            placeholder="请选择货位并绘制地图"
            :rules="[{ required: true, message: '请选择货位' }]"
          >
            <template #label> 货位<span class="xing">*</span></template>
          </van-field>
          <van-popup
            v-model:show="showSelectStoragePopup"
            position="bottom"
            round
            duration="0"
            class="bg-slate-400 h-[calc(100vh-100px)]"
          >
            <SelectStorage
              :positionInfo="formData.positionInfo"
              :storageId="formData.positionInfo.storageId"
              :positionId="formData.positionInfo.id"
              :transportBillId="billInfo.transportBillId"
              @isOpen="isSelectStorageOpen"
              @selectedStorage="selectedStorage"
            ></SelectStorage>
          </van-popup>
          <van-field
            readonly
            name="tallyPackageType"
            is-link
            placeholder="请选择包装"
            v-model="formData.tallyPackageTypeName"
            @click="showSelectPackageTypePopup = true"
            :rules="[{ required: true, message: '请选择包装' }]"
          >
            <template #label> 包装<span class="xing">*</span></template>
          </van-field>
          <van-popup
            v-model:show="showSelectPackageTypePopup"
            position="bottom"
            round
            duration="0"
            :style="{ height: 'auto' }"
          >
            <SelectPackageType
              :packageType="{
                value: formData.tallyPackageType,
                text: formData.tallyPackageTypeName
              }"
              @isOpen="isSelectPackageTypeOpen"
              @selectedPackageType="selectedPackageType"
            ></SelectPackageType>
          </van-popup>
          <van-field
            name="piece"
            v-model="formData.tallyPiece"
            label="理货件数"
            placeholder="请输入件数"
            :rules="[{ validator, message: '请输入件数' }]"
          >
            <template #label> 理货件数<span class="xing">*</span></template>
          </van-field>
          <van-field
            name="ton"
            :border="false"
            v-model="formData.tallyTon"
            @focus="setTon"
            label="理货吨数"
            placeholder="请输入吨数"
            :rules="[{ validator, message: '请输入吨数' }]"
          >
            <template #label> 理货吨数<span class="xing">*</span></template>
          </van-field>
        </van-form>
        <yard-map-v2
          v-if="showYard"
          :positionInfo="formData.positionInfo"
          :goodsPositionId="formData.goodsPositionId"
          @closeMap="showYard = false"
          @saved="onSelectedArea"
        ></yard-map-v2>
      </div>
    </van-config-provider>
  </div>
</template>

<style scoped></style>
